const redis = require('redis')
const { REDIS_CONF } = require('../config/db')
const client = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)

// 监听错误
client.on('error', err => {
  throw new Error(err)
})

// 新建数据
const set = (key, value) => {
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  client.set(key, value)
}

// 获取数据
const get = async (key) => {
  return new Promise((resolve, reject) => {
    client.get(key, (err, data) => {
      if (err) reject(err)
      if (data == null) {
        resolve(null)
        return
      }
      resolve(JSON.parse(data))
    })
  })
}

module.exports = {
  set,
  get
}
